package com.platform.usercenter.controller;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSON;
import com.platform.common.core.constant.HttpStatus;
import com.platform.common.core.constant.SecurityConstants;
import com.platform.common.core.constant.ServiceNameConstants;
import com.platform.common.core.constant.UserConstants;
import com.platform.common.core.domain.R;
import com.platform.common.core.enums.MenuEndPointEnum;
import com.platform.common.core.exception.ServiceException;
import com.platform.common.core.utils.StringUtils;
import com.platform.common.core.utils.file.FileTypeUtils;
import com.platform.common.core.utils.file.MimeTypeUtils;
import com.platform.common.core.web.controller.BaseController;
import com.platform.common.core.web.domain.AjaxResult;
import com.platform.common.security.annotation.RequiresPermissions;
import com.platform.common.security.utils.SecurityUtils;
import com.platform.file.api.remote.api.RemoteFileService;
import com.platform.file.api.remote.vo.SysFile;
import com.platform.system.api.remote.api.RemoteSystemService;
import com.platform.system.api.remote.vo.SysDictData;
import com.platform.usercenter.domain.SysMenuTreeDTO;
import com.platform.usercenter.domain.query.SysMenuQuery;
import com.platform.usercenter.domain.request.GetRoutersRequest;
import com.platform.usercenter.domain.vo.TreeSelect;
import com.platform.usercenter.service.ISysMenuService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.Lists;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description: 菜单接口
 * @Author: wcs
 * @Date: 2024-11-14 15:04:32
 **/
@Slf4j
@RestController
@RequestMapping("/menu")
public class SysMenuController extends BaseController {
    @Resource
    private ISysMenuService menuService;

    @Resource
    private RemoteFileService remoteFileService;

    @Resource
    private RemoteSystemService remoteSystemService;


    /**
     * 获取菜单列表
     */
    @GetMapping("/list")
    public AjaxResult list(SysMenuQuery menuQuery) {
        Long userId = SecurityUtils.getLoginUser().getSysUser().getUserId();
        List<SysMenuTreeDTO> menus = menuService.selectMenuList(menuQuery, userId, SecurityUtils.getLoginUser().getOrgId());
        return success(menus);
    }

    /**
     * 根据菜单编号获取详细信息
     */
    @RequiresPermissions("system:menu:query")
    @GetMapping(value = "/{menuId}")
    public AjaxResult getInfo(@PathVariable Long menuId) {
        return success(menuService.selectMenuById(menuId));
    }

    /**
     * 获取菜单下拉树列表
     */
    @GetMapping("/treeselect")
    public AjaxResult treeSelect() {
        Long userId = SecurityUtils.getLoginUser().getSysUser().getUserId();
        List<SysMenuTreeDTO> menus = menuService.selectMenuByUserId(userId, SecurityUtils.getLoginUser().getOrgId(), MenuEndPointEnum.PDA.name());
        // 添加 菜单所属系统说明 start
        R<List<SysDictData>> systemTypeList = remoteSystemService.getDictInfo("sys_system_type", SecurityConstants.INNER);
        if (HttpStatus.SUCCESS != systemTypeList.getCode()) {
            throw new ServiceException(systemTypeList.getCode() + systemTypeList.getMsg());
        }
        Map<String, String> systemTypeMap = new HashMap<>();
        if (systemTypeList.getData() != null && !systemTypeList.getData().isEmpty()) {
            List<SysDictData> list = systemTypeList.getData();
            for (SysDictData systemTypeVO : list) {
                systemTypeMap.put(systemTypeVO.getDictValue(), systemTypeVO.getDictLabel());
            }
        }
        if ((menus != null && !menus.isEmpty())) {
            for (SysMenuTreeDTO sysMenuVO : menus) {
                String systemType = sysMenuVO.getSystemType();
                if (StringUtils.isNotEmpty(systemType)) {
                    String systemTypeName = systemTypeMap.get(systemType);
                    sysMenuVO.setMenuName(sysMenuVO.getMenuName() + "(" + systemTypeName + ")");
                }
            }
        }
        // 添加 菜单所属系统说明 end
        return success(menuService.buildMenuTreeSelect(menus));
    }

    /**
     * 加载对应角色菜单列表树
     */
    @GetMapping(value = "/roleMenuTreeselect/{roleId}")
    public AjaxResult roleMenuTreeselect(@PathVariable("roleId") Long roleId) {
        Long userId = SecurityUtils.getLoginUser().getSysUser().getUserId();
        SysMenuQuery menuQuery = new SysMenuQuery();
        menuQuery.setStatus("0");
        List<SysMenuTreeDTO> menus = menuService.selectMenuList(menuQuery, userId, SecurityUtils.getLoginUser().getOrgId());
        // 添加 菜单所属系统说明 start
        R<List<SysDictData>> systemTypeList = remoteSystemService.getDictInfo("sys_system_type", SecurityConstants.INNER);
        if (HttpStatus.SUCCESS != systemTypeList.getCode()) {
            throw new ServiceException(systemTypeList.getCode() + systemTypeList.getMsg());
        }
        Map<String, String> systemTypeMap = new HashMap<>();
        if (systemTypeList.getData() != null && !systemTypeList.getData().isEmpty()) {
            List<SysDictData> list = systemTypeList.getData();
            for (SysDictData systemTypeVO : list) {
                systemTypeMap.put(systemTypeVO.getDictValue(), systemTypeVO.getDictLabel());
            }
        }
        if ((menus != null && !menus.isEmpty())) {
            for (SysMenuTreeDTO sysMenuVO : menus) {
                String systemType = sysMenuVO.getSystemType();
                if (StringUtils.isNotEmpty(systemType)) {
                    String systemTypeName = systemTypeMap.get(systemType);
                    sysMenuVO.setMenuName(sysMenuVO.getMenuName() + "(" + systemTypeName + ")");
                }
            }
        }
        // 添加 菜单所属系统说明 end
        AjaxResult ajax = AjaxResult.success();
        ajax.put("checkedKeys", menuService.selectMenuListByRoleId(roleId));
        List<TreeSelect> tree;
        if (CollectionUtils.isEmpty(menus)) {
            tree = Lists.newArrayList();
        } else {
            tree = menus.stream().map(TreeSelect::new).collect(Collectors.toList());
        }
        ajax.put("menus", tree);
        return ajax;
    }

    /**
     * 加载对应角色菜单列表树
     */
    @PostMapping(value = "/roleMenuTreeList")
    public AjaxResult roleMenuTreeList(@RequestParam("roleId") Long roleId, @RequestParam("orgId") Long orgId) {
        Long userId = SecurityUtils.getLoginUser().getSysUser().getUserId();
        SysMenuQuery menuQuery = new SysMenuQuery();
        menuQuery.setStatus("0");
        if (ObjectUtil.isEmpty(orgId)) {
            orgId = SecurityUtils.getLoginUser().getOrgId();
        }
        List<SysMenuTreeDTO> menus = menuService.selectMenuListByGranded(menuQuery, userId, orgId);
        // 添加 菜单所属系统说明 start
        R<List<SysDictData>> systemTypeList = remoteSystemService.getDictInfo("sys_system_type", SecurityConstants.INNER);
        if (HttpStatus.SUCCESS != systemTypeList.getCode()) {
            throw new ServiceException(systemTypeList.getCode() + systemTypeList.getMsg());
        }
        Map<String, String> systemTypeMap = new HashMap<>();
        if (systemTypeList.getData() != null && !systemTypeList.getData().isEmpty()) {
            List<SysDictData> list = systemTypeList.getData();
            for (SysDictData systemTypeVO : list) {
                systemTypeMap.put(systemTypeVO.getDictValue(), systemTypeVO.getDictLabel());
            }
        }
        if ((menus != null && !menus.isEmpty())) {
            for (SysMenuTreeDTO sysMenuVO : menus) {
                String systemType = sysMenuVO.getSystemType();
                if (StringUtils.isNotEmpty(systemType)) {
                    String systemTypeName = systemTypeMap.get(systemType);
                    sysMenuVO.setMenuName(sysMenuVO.getMenuName() + "(" + systemTypeName + ")");
                }
            }
        }
        // 添加 菜单所属系统说明 end
        AjaxResult ajax = AjaxResult.success();
        ajax.put("checkedKeys", menuService.selectMenuListByRoleId(roleId));
        List<TreeSelect> tree;
        if (CollectionUtils.isEmpty(menus)) {
            tree = Lists.newArrayList();
        } else {
            tree = menus.stream().map(TreeSelect::new).collect(Collectors.toList());
        }
        ajax.put("menus", tree);
        return ajax;
    }

    /**
     * 新增菜单
     */
    @RequiresPermissions("system:menu:add")
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysMenuTreeDTO menu) {
        if (!menuService.checkMenuNameUnique(menu)) {
            return error("新增菜单'" + menu.getMenuName() + "'失败，菜单名称已存在");
        }
        if (!menuService.checkMenuPathUnique(menu)) {
            return error("新增菜单'" + menu.getMenuName() + "'失败，路由地址已存在");
        } else if (UserConstants.YES_FRAME.equals(menu.getIsFrame()) && !StringUtils.ishttp(menu.getPath())) {
            return error("新增菜单'" + menu.getMenuName() + "'失败，地址必须以http(s)://开头");
        }
        menu.setCreateBy(SecurityUtils.getUsername());
        return toAjax(menuService.insertMenu(menu));
    }

    /**
     * 修改菜单
     */
    @RequiresPermissions("system:menu:edit")
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysMenuTreeDTO menu) {
        if (!menuService.checkMenuNameUnique(menu)) {
            return error("修改菜单'" + menu.getMenuName() + "'失败，菜单名称已存在");
        }
        if (!menuService.checkMenuPathUnique(menu)) {
            return error("修改菜单'" + menu.getMenuName() + "'失败，路由地址已存在");
        } else if (UserConstants.YES_FRAME.equals(menu.getIsFrame()) && !StringUtils.ishttp(menu.getPath())) {
            return error("修改菜单'" + menu.getMenuName() + "'失败，地址必须以http(s)://开头");
        } else if (menu.getMenuId().equals(menu.getParentId())) {
            return error("修改菜单'" + menu.getMenuName() + "'失败，上级菜单不能选择自己");
        }
        menu.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(menuService.updateMenu(menu));
    }

    /**
     * 删除菜单
     */
    @RequiresPermissions("system:menu:remove")
    @DeleteMapping("/{menuId}")
    public AjaxResult remove(@PathVariable("menuId") Long menuId) {
        if (menuService.hasChildByMenuId(menuId)) {
            return warn("存在子菜单,不允许删除");
        }
        if (menuService.checkMenuExistRole(menuId)) {
            return warn("菜单已分配,不允许删除");
        }
        return toAjax(menuService.deleteMenuById(menuId));
    }

    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @GetMapping({"getRouters"})
    public AjaxResult getRouters(GetRoutersRequest request) {
        Long userId = SecurityUtils.getLoginUser().getSysUser().getUserId();
        Long orgId = SecurityUtils.getLoginUser().getOrgId();
        List<SysMenuTreeDTO> menus = this.menuService.selectMenuTreeByUserIdRouter(userId, orgId, request.getEndPoint());
        menus.forEach(item -> {
            if (StringUtils.equals(item.getMenuName(), "工具栏")) {
                item.setVisible("1");
            }
        });
        return AjaxResult.success(this.menuService.buildMenusPc(menus, request.getHost(), request.getEndPoint(), null));
    }

    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @GetMapping({"getWeiXinRouters"})
    public AjaxResult getWeiXinRouters() {
        Long userId = SecurityUtils.getLoginUser().getSysUser().getUserId();
        Long loginOrgId = SecurityUtils.getLoginUser().getOrgId();
        List<SysMenuTreeDTO> menus = this.menuService.selectMenuTreeByUserIdRouter(userId, loginOrgId, MenuEndPointEnum.WX_XCX.name());
        return AjaxResult.success(this.menuService.buildMenusWeiXin(menus, MenuEndPointEnum.WX_XCX.name(), null));
    }

    /**
     * 获取游客路由信息
     *
     * @return 路由信息
     */
    @GetMapping({"getWeiXinRoutersByGuest"})
    public AjaxResult getWeiXinRoutersByGuest() {
        List<SysMenuTreeDTO> menus = this.menuService.selectMenuTreeByUserIdRouterByGuest(MenuEndPointEnum.WX_XCX.name());
        return AjaxResult.success(this.menuService.buildMenusWeiXin(menus, MenuEndPointEnum.WX_XCX.name(), null));
    }

    /**
     * 获取app路由信息
     *
     * @return 路由信息
     */
    @GetMapping({"getAppRouters"})
    public AjaxResult getAppRouters() {
        Long userId = SecurityUtils.getLoginUser().getSysUser().getUserId();
        log.info("用户ID:{}", userId.toString());
        log.info("获取用户信息为:{}", JSON.toJSONString(SecurityUtils.getLoginUser()));
        // 当前组织
        Long orgId = SecurityUtils.getLoginUser().getOrgId();
        List<SysMenuTreeDTO> menus = this.menuService.selectAppMenuTreeByUserId(userId, orgId, MenuEndPointEnum.PDA.name());
        return AjaxResult.success(this.menuService.buildMenus(menus, MenuEndPointEnum.PDA.name(), null));
    }

    /**
     * 图标icon图片上传
     */
    @PostMapping("/iconUpload")
    public AjaxResult iconUpload(@RequestParam("iconfile") MultipartFile file) {
        if (!file.isEmpty()) {
            String extension = FileTypeUtils.getExtension(file);
            if (!StringUtils.equalsAnyIgnoreCase(extension, MimeTypeUtils.IMAGE_EXTENSION)) {
                return error("文件格式不正确，请上传" + Arrays.toString(MimeTypeUtils.IMAGE_EXTENSION) + "格式");
            }
            R<SysFile> fileResult = remoteFileService.upload(file, ServiceNameConstants.USER_CENTER_SERVICE, ServiceNameConstants.USER_CENTER_SERVICE, "1");
            if (StringUtils.isNull(fileResult) || StringUtils.isNull(fileResult.getData())) {
                return error("文件服务异常，请联系管理员");
            }
            String url = fileResult.getData().getUrl();
            if (StringUtils.isNotEmpty(url)) {
                return AjaxResult.success(url);
            } else {
                return error();
            }
        }
        return error("上传图片异常，请联系管理员");
    }

    @GetMapping(value = "getChildMenu/{menuId}")
    public AjaxResult getChildMenu(@PathVariable Long menuId) {
        return success(menuService.getAllChildMenu(menuId));
    }

    /**
     * 保存按钮权限
     *
     * @param parentId 父ID
     * @param prefix   前缀
     * @return 操作完成
     */
    @GetMapping(value = "/saveButtonPermissions/{parentId}/{prefix}")
    public AjaxResult saveButtonPermissions(@PathVariable("parentId") Long parentId, @PathVariable("prefix") String prefix) {
        menuService.saveButtonPermissions(parentId, prefix);
        return AjaxResult.success();
    }
}
